package com.ruoyi.base.utils.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * 异步工具类(不支持事务)
 *
 * @author lcf
 */
public class ThreadUtils {
    /**
     * 异步执行子任务，并且等待全部执行完成
     * 不支持事务
     */
    public static <T> void asyncAll(List<Supplier<T>> consumerList, Consumer<T> consumer) {
        Executor executor = ThreadPoolManager.getPoolExecutor();

        List<CompletableFuture> futureList = new ArrayList<>();

        consumerList.forEach(x -> futureList.add(
                CompletableFuture.supplyAsync(x, executor)
                        .thenAccept(consumer)
                        .exceptionally(e -> {
                            throw new RuntimeException(e);
                        })
        ));
        //等待全部完成
        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])).join();
    }

    /**
     * 异步执行子任务，并且等待全部执行完成
     * 不支持事务
     */
    public static <T> List<T> asyncAll(List<Supplier<T>> consumerList) {
        List<T> list = new CopyOnWriteArrayList<>();
        asyncAll(consumerList, list::add);
        return list;
    }

    /**
     * 异步执行子任务，并且等待全部执行完成
     * 不支持事务
     */
    public static <T> List<T> asyncListAll(List<Supplier<List<T>>> consumerList) {
        List<T> list = new CopyOnWriteArrayList<>();
        asyncAll(consumerList, list::addAll);
        return list;
    }

    /**
     * 异步执行任务
     * 不支持事务
     */
    public static void addTask(Runnable runnable) {
        ThreadPoolManager.newInstance().addExecuteTask(runnable);
    }

    /**
     * 异步执行任务
     * 不支持事务
     */
    public static <T> CompletableFuture<T> addTask(Supplier<T> supplier) {
        return CompletableFuture.supplyAsync(supplier, ThreadPoolManager.getPoolExecutor());
    }
}
